﻿
using MailBox.App_Code;
using MailBox.App_Code.dto;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.Tracking
{
    public partial class inbounce : System.Web.UI.Page
    {
        DataUtils utils = new DataUtils();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //string _event = Request.Params["event"];
                //string messageId = Request.Params["message-id"];
                //string message_headers = Request.Params["message-headers"];
                //logs_traching.Info("event:" + _event + " header:" + message_headers);
                //if (_event + "" != "" && messageId + "" != "")
                //{
                //    TrackingUtils.TrackingItem(_event, messageId, Request.Params["domain"] + "", Request.Params["recipient"] + "");
                //}
                NameValueCollection param = Request.Params;
                if (param.Count == 0) return;
                for (int i = 0; i < param.Count; i++)
                {
                    Common.logs(null, param.GetKey(i), null, Common.logType.tracking);
                    Common.logs(null, param.GetValues(i)[0], null, Common.logType.tracking);

                }
                try
                {
                    /*
                     * 2014-09-21 07:30:25,819 - X-Mailgun-Incoming
                        2014-09-21 07:30:25,819 - Yes
                        2014-09-21 07:30:25,820 - X-Mailgun-Sflag
                        2014-09-21 07:30:25,820 - No
                        2014-09-21 07:30:25,820 - X-Mailgun-Sscore
                        2014-09-21 07:30:25,820 - 0.0
                        2014-09-21 07:30:25,820 - X-Mailgun-Spf
                        2014-09-21 07:30:25,821 - Neutral
                     * */

                    string from = Request.Params["sender"];
                    if (from.Split(',').Length > 1)
                        from = from.Split(',')[0].IndexOf("bounce") >= 0 ? from.Split(',')[1] : from.Split(',')[0];
                    string sendername = Request.Params["From"];
                    string recipient = Request.Params["recipient"];
                    string subject = Request.Params["Subject"];
                    string body_plain = Request.Params["body-plain"] + "";
                    string body_html = Request.Params["body-html"] + "";
                    string stripped_html = Request.Params["stripped-html"] + "";
                    if (string.IsNullOrWhiteSpace(body_html))
                        if (string.IsNullOrWhiteSpace(stripped_html))
                            body_html = body_plain;
                        else body_html = stripped_html;
                    HttpFileCollection files = Request.Files;
                    string folder = "AttachFiles/" + recipient + "/" + Guid.NewGuid().ToString();
                    string path = Server.MapPath(folder);
                    string attachfiles = "";
                    if (Request.Files.Count > 0)
                    {
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                        //int totalLength = files.AllKeys.Select(k => files[k]).Sum(f => f.ContentLength);
                        foreach (string file in files.AllKeys)
                        {
                            //Common.logs(files[file].FileName, null, Common.logType.info);
                            string filename = files[file].FileName;
                            if (filename.IndexOf('/') < 0)
                            {
                                Common.logs(null, filename, null, Common.logType.info);
                                Common.logs(null, Path.Combine(path, filename), null, Common.logType.info);
                                files[file].SaveAs(Path.Combine(path, filename));
                                attachfiles += filename + ",";
                            }
                        }
                    }
                    //message-headers - ["X-Mailgun-Sflag", "No"]
                    foreach (string reciever in recipient.Split(','))
                    {
                        InboxDTO inbox = new InboxDTO();
                        inbox.body = body_plain;
                        inbox.senderName = sendername.Split(',')[0];
                        inbox.body_html = body_html;
                        inbox.sender = from;
                        inbox.subject = subject.Split(',')[0];
                        inbox.reciever = reciever.Trim();
                        if (Request.Files.Count > 0)
                            inbox.FileAttached = folder;

                        utils.AddInbox(inbox);
                    }

                    Common.logs(null, "from:" + from, null, Common.logType.info);
                    Common.logs(null, "recipient:" + recipient, null, Common.logType.info);
                    Common.logs(null, "subject:" + subject, null, Common.logType.info);
                    Common.logs(null, "body_plain:" + body_plain, null, Common.logType.info);
                }
                catch (Exception ex)
                {
                    Common.logs(null, "Load Error:", ex, Common.logType.error);
                }
            }
        }
    }
}